<template>
  <div @tap="getCode" :class="{point: isls}">{{codeMsg}}</div>
</template>

<script>
  import axios from '../../config/axios'
  import storage from 'storejs'
  import { getToken,regPhone } from "../../config/utils"
  import API from '../../config/api'
  
  export default {
    name: 'Captcha',
    data: function () {
      return {
        token: '',
        isls: true,   //是否可以点击发送
        codeMsg: '获取验证码'
      }
    },
    props: [
      'phonenumber', // 输入的电话号码
      'type'        //属于注册获取还是登录获取
    ],
    created: function () {
      if (storage.get(this.type) > 0) {
        this.countDown();
      }
    },
    mounted: function () {
      getToken().then((res) => {
        this.token = res;
      });
    },
    methods: {
      getCode: function () {
        if (storage.get(this.type) > 0) {
          this.$msg('您上次获取验证码还未超过一分钟');
          return;
        }
        
        if (!regPhone(this.phonenumber)) {
          this.$msg('请输入正确的手机号码');
          return false;
        }
  
        var url = API.getAuthCode;
  
        axios.post(url, {
          token: this.token,
          phonenumber: this.phonenumber,
          type: this.type || 'login'
        }).then((res) => {
    
          if (res.code == 1) {
            this.countDown();
            this.$msg('验证码已发送到你的手机。');
          }
    
          if (res.code == 3) {
            this.$msg('该用户已注册');
          }
    
          if (res.code == 5) {
            this.$msg('当天验证码使用次数已用完');
          }
    
          if (res.code == 6) {
            this.$msg('验证码已过期');
          }
    
          if (res.code == 7) {
            this.$msg('每小时只能使用5次，您已经用完了');
          }
    
        }).catch((err) => {
          this.$msg(err);
        })
      },
      countDown: function () {
        const TIME_COUNT = storage.get(this.type) || 60;
        let count = TIME_COUNT;
        this.codeMsg = TIME_COUNT + 's';
        if (!this.timer) {
          this.timer = setInterval(() => {
            if (count > 0 && count <= TIME_COUNT) {
              this.isls = false;
              count--;
              storage.set(this.type, count);
              this.codeMsg = count + 's';
            } else {
              this.isls = true;
              this.codeMsg = '重新获取';
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
      }
    }
  }
</script>

<style scoped>

</style>
